using CatLib;
using CatLib.Container;
using Cysharp.Threading.Tasks;
using GameFramework.App;
using GameFramework.Event;
using GameFramework.Fsm;
using GameFramework.Procedure.Attribute;
using GameFramework.Procedure.Fsm;

namespace GameLogic.Launch
{
    /// <summary>
    /// 更新资源流程
    /// </summary>
    [Procedure]
    public sealed class UpdateResourceProcedure : AFsmProcedure
    {
        private bool m_UpdateComplete;
        
        public override void OnEnter(IFsm fsm)
        {
            base.OnEnter(fsm);

            m_UpdateComplete = false;
            
            EventService.That.Raise(this, LaunchStepUpdatedEvent.Acquire(LaunchStep.UpdateResource));
            UpdateResourceAsync().Forget();
        }

        public override void OnUpdate(IFsm fsm, float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(fsm, elapseSeconds, realElapseSeconds);

            if (!m_UpdateComplete)
                return;
            
            // 更新完成需要热重载游戏
            GameApp.That.Reboot();
        }

        private async UniTask UpdateResourceAsync()
        {
            // TODO 直接当作更新成功
            m_UpdateComplete = true;
            EventService.That.Raise(this, LaunchStepUpdatedEvent.Acquire(LaunchStep.UpdateResource, 1f));
        }
    }
}